#!/bin/bash

#author Hopeful

# Elasticsearch Host and Port
ELASTICSEARCH_HOST="localhost"
ELASTICSEARCH_PORT="9200"

# Calculate Date 180 days ago
DELETE_DATE=$(date -d "180 days ago" +%Y.%m.%d)

# Get list of indices starting with "log-"
indices=$(curl -s -X GET "http://$ELASTICSEARCH_HOST:$ELASTICSEARCH_PORT/_cat/indices/log-gk-*?h=index" | grep -E "^log-gk" | awk '{print $1}')

# Delete old indices
for index in $indices; do
    index_date=$(echo "$index" | sed 's/.*-\([0-9]\{4\}\.[0-9]\{2\}\.[0-9]\{2\}\)$/\1/')
    if [[ "$index_date" < "$DELETE_DATE" ]]; then
        echo "Deleting index: $index"
        curl -X DELETE "http://$ELASTICSEARCH_HOST:$ELASTICSEARCH_PORT/$index"
    fi
done